package com.smartwebee.android.blespp.hospital.account;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.smartwebee.android.blespp.R;
import com.smartwebee.android.blespp.databinding.ActivityRegisterBinding;
import com.smartwebee.android.blespp.eventbusclass.RegisterSucEvent;
import com.smartwebee.android.blespp.hospital.BaseActivity;
import com.smartwebee.android.blespp.hospital.HospitalMainActivity;
import com.smartwebee.android.blespp.http.VolleyReqQueue;
import com.smartwebee.android.blespp.resp.RegisterResp;
import com.smartwebee.android.blespp.utils.UIUtils;
import com.smartwebee.android.blespp.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class RegisterActivity extends BaseActivity implements View.OnClickListener, Response.Listener<String>, Response.ErrorListener {

    ActivityRegisterBinding binding;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_register);
        TAG = "RegisterActivity";
        initView();
        initData();
    }

    private void initData() {
        // Instantiate the RequestQueue.
        requestQueue = VolleyReqQueue.getInstance(this).getRequestQueue();
    }

    private void httpRegister() {
        showLoading();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Utils.baseUrl + Utils.register,
                this, this) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                JSONObject object = new JSONObject();
                try {
                    object.put("password", binding.editPwd.getText().toString());
                    object.put("sex", binding.editSex.getText().toString());
                    object.put("uname", binding.editName.getText().toString());
                    object.put("name", binding.editCardNum.getText().toString());
                    object.put("weight", binding.editWeight.getText().toString());
                    object.put("sn", binding.editCardNum.getText().toString());
                    object.put("email", binding.editEmail.getText().toString());
                    object.put("age", binding.editAge.getText().toString());
                    object.put("height", binding.editHeight.getText().toString());
                    object.put("bmi", binding.tvBmiValue.getText().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("value", object.toString());
                map.put("id", binding.editDoctor.getText().toString());
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    private void initView() {
        binding.btnBack.setOnClickListener(this);
        binding.btnRegister.setOnClickListener(this);
        binding.editHeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBmi();
            }
        });
        binding.editWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBmi();
            }
        });
    }

    private void setBmi() {
        if (!Utils.checkEditEmpty(binding.editHeight) && !Utils.checkEditEmpty(binding.editWeight)) {
            binding.tvBmiValue.setText(getBmi(binding.editHeight.getText().toString(), binding.editWeight.getText().toString()));
        }
    }

    private String getBmi(String height, String weight) {
        Double h = Utils.toDouble(height);
        Double w = Utils.toDouble(weight);
        if (h != null && w != null && h != 0) {
            return Utils.formatDouble(w / (h * h));
        }
        return "";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_register:
                if (checkInput()) {
                    httpRegister();
                } else {
                    UIUtils.showTips(RegisterActivity.this, "请补充注册信息");
                }
                break;
        }
    }

    private boolean checkInput() {
        return !TextUtils.isEmpty(binding.editCardNum.getText().toString())
                && !TextUtils.isEmpty(binding.editDeviceNum.getText().toString())
                && !TextUtils.isEmpty(binding.editDoctor.getText().toString())
                && !TextUtils.isEmpty(binding.editEmail.getText().toString())
                && !TextUtils.isEmpty(binding.editName.getText().toString())
                && !TextUtils.isEmpty(binding.editSex.getText().toString())
                && !TextUtils.isEmpty(binding.editAge.getText().toString())
                && !TextUtils.isEmpty(binding.editHeight.getText().toString())
                && !TextUtils.isEmpty(binding.editWeight.getText().toString())
                && !TextUtils.isEmpty(binding.editPwd.getText().toString());
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        showLoading();
        UIUtils.showToast(RegisterActivity.this, error.toString());
    }

    @Override
    public void onResponse(String response) {
        Log.i("myResp", response);
        showLoading();
        RegisterResp registerResp = new Gson().fromJson(response, RegisterResp.class);
        if (Utils.parseData(registerResp)) {
            //存储登录信息
            Utils.registerResp = registerResp;
            UIUtils.showToast(RegisterActivity.this, "注册成功");
            startActivity(new Intent(RegisterActivity.this, HospitalMainActivity.class));
            EventBus.getDefault().post(new RegisterSucEvent());
            finish();
        } else {
            UIUtils.showToast(RegisterActivity.this, registerResp.getMsg());
        }
    }
}
